package com.bolt.report.engine.calculator;

import com.bolt.common.reflect.ObjectUtil;
import com.bolt.report.engine.BindData;
import com.bolt.report.engine.Calculator;
import com.bolt.report.engine.fill.FillContext;
import com.bolt.report.engine.fill.FillReturnValue;
import com.bolt.report.engine.model.Cell;
import com.bolt.report.engine.model.Expression.CalculatorExpression;
import com.bolt.report.util.ToolUtil;

import java.math.BigDecimal;
import java.util.Collection;

public class SumCalculator implements Calculator {

    @Override
    public Object evaluate(FillContext context, BindData data, CalculatorExpression expr, Cell cell) {
        BigDecimal result = new BigDecimal(0);
        if (ObjectUtil.isNotNull(data.getData())) {
            Object bindData = data.getData();
            if (bindData instanceof Collection) {
                for (Object value : (Collection) bindData) {
                    if (value == null || value.toString().equals("")) {
                        continue;
                    }
                    result = result.add(ToolUtil.toBigDecimal(value));
                }
            } else {
                result = ToolUtil.toBigDecimal(bindData);
            }
            return result;
        } else {
            FillReturnValue values = context.getReturnValue(data.getKey());
            int start = data.start(), end = data.end();
            while (values.next(start, end)) {
                Object value = values.getValue(expr.getExpr());
                if (value == null || value.toString().equals("")) {
                    continue;
                }
                result = result.add(ToolUtil.toBigDecimal(value));
                start++;
            }
            return result;
        }

    }
}